#include "ThreadPool.h"


ThreadPool::ThreadPool(int numThreads/* = std::thread::hardware_concurrency()*/)
: m_queue(MAX_TASK_COUNT)
{
    Start(numThreads);
}

//销毁线程池
ThreadPool::~ThreadPool()
{
    Stop();
}

//终止所有线程，call_once保证函数只执行一次
void ThreadPool::Stop()
{
    std::call_once(m_flag, [this](){ StopThreadGroup(); });
}

//添加任务,普通版本
void ThreadPool::AddTask(const Task &task)
{
    m_queue.Put(task);
}

//添加任务，右值引用版本
void ThreadPool::AddTask(Task && task)
{
    m_queue.Put(std::forward<Task>(task));
}

//停止线程池
void ThreadPool::StopThreadGroup()
{
    m_queue.Stop();
    m_running = false;
    for (auto thread : m_threadGroup)
    {
        if (thread)
        {
            thread->join();
        }
    }
    m_threadGroup.clear();
}

void ThreadPool::Start(int numThreads)
{
    m_running = true;
    for (int i = 0; i < numThreads; ++i)
    {
        //智能指针管理，并给出构建线程的参数，线程调用函数和参数
        std::cout << "create thread pool " << i << std::endl;
        m_threadGroup.push_back(std::make_shared<std::thread>(&ThreadPool::RunInThread, this));
    }

}

//一次取出所有事件
void ThreadPool::RunInThreadList()
{
    while (m_running)
    {
        std::list<Task> list;
        std::cout << "take" << std::endl;
        m_queue.Take(list);
        for (auto &task : list)
        {
            if (!m_running)
            {
                return;
            }
            task();
        }
    }
}

//一次取出一个事件
void ThreadPool::RunInThread()
{
    std::cout << m_queue.Size() << std::endl;
    while (m_running)
    {
        Task task;
        if (!m_running)
        {
            return;
        }
        m_queue.Take(task);
    }
}